package com.goldcn.classify.service;

import com.goldcn.classify.dao.ClassifyMapper;
import com.goldcn.classify.dao.ClassifyStyleMapper;
import com.goldcn.classify.model.Classify;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.config.PropertiesConfig;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.util.CommonTools;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("classifyService")
@Transactional
public class ClassifyService {

    @Autowired
    private ClassifyMapper classifyMapper;

    @Autowired
    private ClassifyStyleMapper classifyStyleMapper;

//    @Autowired
//    private ClassifynecklaceService classifynecklaceService;

    private Classify classify;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private PropertiesConfig cfg;

    private Logger logger = Logger.getLogger(ClassifyService.class);

    private List<Map<String, Object>> listMap;

    private Map<String, Object> clazzColorMap;

    /**
     * 查询所有品类
     *
     * @param code
     * @return
     */
    public List<Map<String, Object>> selectedall(String code) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("code", code);
        return classifyMapper.selectedall(param);
    }

    /**
     * 查询所有品类
     *
     * @param code
     * @return
     */
    public List<Map<String, Object>> selectedall(String code, String clazzID) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("code", code);
        param.put("clazzID", clazzID);
        return classifyMapper.selectedall(param);
    }


    /**
     * 查询适应平台类型的所有末端品类
     *
     * @param code
     * @return
     */
    public List<Classify> selectTipClassify(String code) {
        try {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("code", code);
            return classifyMapper.selectTipClassify(parm);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.parmError);
        }
    }

    /**
     * 查询适应平台类型的所有一级品类
     *
     * @param code
     * @return
     */
    public Object selectClassifyList(String code) {
        //0、通用1、2、3、各种平台4、所有数据
        try {
            if (code.equals("6")) {//私享品分类
                //跨服务请求扣点值
                List<Classify> classifyList = classifyMapper.selectClassifyList(Integer.parseInt(code));

                //return this.sxpClazzResultInfo(classifyList);

                return  classifyList ;

            } else {
                return classifyMapper.selectClassifyList(Integer.parseInt(code));
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.parmError);
        }
    }

    /**
     * 查询树结构的
     *
     * @param code
     * @param type 0 品类-款式 1 品类-款式-成色
     * @return
     */
    public Object selectColorStyleByClassify(String code, int type, String clazzID) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        listMap = selectedall(code, clazzID);
        if (CommonUtils.isNotEmpty(clazzID)) {
            listMap.get(0).put("clazzparentid", "");
        }
        switch (type) {
            case 0:
                list = getChildren("", null);
                break;
            case 1:
                //查询品类-成色关联
//                List<Dto_ClazzColor> clazzColorList = (List<Dto_ClazzColor>)
//                        classifynecklaceService.selectClassifyColor(code, clazzID);
//                //list转索引map
//                clazzColorMap = new HashMap<String, Object>();
//                for (Dto_ClazzColor clazzColor : clazzColorList) {
//                    clazzColorMap.put(clazzColor.getClassify().getClazzID(), clazzColor.getColorList());
//                }
//                list = getChildrenWithColor("", null);
                break;
        }
        return list;
    }

    /**
     * 查询 品类-款式-成色
     *
     * @param code
     * @return
     */
    public Object selectColorStyleByClassifyNoTree(String code, String clazzID) {
        return classifyMapper.selectColorStyleByClassifyNoTree(code, clazzID);
    }

    /**
     * 品类树结构with分销信息
     *
     * @param parentID
     * @param shopID
     * @return
     */
    public List<Map<String, Object>> loadDistributionCase(String parentID, String shopID) {
        listMap = selectedall("1");
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        Map<String, String> ids = new HashMap<String, String>();
        ids.put("shopId", shopID);
        for (Map<String, Object> children : listMap) {
            if (children.get("clazzparentid").equals(parentID)) {
                ids.put("id", children.get("clazzid").toString());
//                Map<String, String> list = (Map<String, String>) restTemplate.postForObject(
//                        cfg.getCommissionUrl() + "/commission/detail/V1", JSONObject.fromObject(ids), Object.class);
//                children.put("distribution", list.get("data"));
                children.put("visibleBool", false);
                maps.add(children);
            }
        }
        if (maps.size() == 0) {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("clazzid", parentID);
            List<Map<String, Object>> stylelist = classifyStyleMapper.loadObjInfo(parm);
            for (Map<String, Object> styMap : stylelist) {
                ids.put("id", styMap.get("gd_styleID").toString());
//                Map<String, String> list = (Map<String, String>) restTemplate.postForObject(
//                        cfg.getCommissionUrl() + "/commission/detail/V1", JSONObject.fromObject(ids), Object.class);
//                styMap.put("distribution", list.get("data"));
                styMap.put("visibleBool", false);
                styMap.put("clazzparentid", parentID);
                maps.add(styMap);
            }
        }
        return maps;
    }

    /**
     * 查询分类是否存在
     *
     * @param clazzid
     * @return
     */
    public Classify checkByPrimaryKey(String clazzid) {
        classify = new Classify();
        classify = classifyMapper.selectByPrimaryKey(clazzid);
        if (classify == null) {
            return null;
        }
        return classify;
    }

    /**
     * 递归组装品类树结构
     *
     * @param parentID
     * @param parent
     * @return
     */
    private List<Map<String, Object>> getChildren(String parentID, Map<String, Object> parent) {
        List<Map<String, Object>> initClassifyList = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> children : listMap) {
            if (children.get("clazzparentid").equals(parentID)) {
                children.put("children", (Object) getChildren(children.get("clazzid").toString(), children));
                initClassifyList.add(children);
            }
        }
        if (initClassifyList.size() == 0) {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("clazzid", parent.get("clazzid").toString());
            parent.put("stylelist", classifyStyleMapper.loadObjInfo(parm));
        }
        return initClassifyList;
    }

    /**
     * 递归组装品类树结构 with 成色
     *
     * @param parentID
     * @param parent
     * @return
     */
    private List<Map<String, Object>> getChildrenWithColor(String parentID, Map<String, Object> parent) {
        List<Map<String, Object>> initClassifyList = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> children : listMap) {
            if (children.get("clazzparentid").equals(parentID)) {
                children.put("children", (Object) getChildrenWithColor(children.get("clazzid").toString(), children));
                initClassifyList.add(children);
            }
        }
        if (initClassifyList.size() == 0) {
            Map<String, String> parm = new HashMap<String, String>();
            String clazzid = parent.get("clazzid").toString();
            parm.put("clazzid", clazzid);
            parent.put("stylelist", classifyStyleMapper.loadObjInfo(parm));
            parent.put("colorList", clazzColorMap.containsKey(clazzid) ? clazzColorMap.get(clazzid) : new ArrayList<Object>());
        }
        return initClassifyList;
    }

    private List<Map<String, Object>> getChildrenWithColor1(Map<String, Object> clazz) {
        List<Map<String, Object>> initClassifyList = new ArrayList<Map<String, Object>>();
        Map<String, String> parm = new HashMap<String, String>();
        String clazzid = clazz.get("clazzid").toString();
        parm.put("clazzid", clazzid);
        clazz.put("stylelist", classifyStyleMapper.loadObjInfo(parm));
        clazz.put("colorList", clazzColorMap.containsKey(clazzid) ? clazzColorMap.get(clazzid) : new ArrayList<Object>());
        initClassifyList.add(clazz);
        return initClassifyList;
    }

    /**
     * 私享品分类携带扣点值
     *
     * @param classifyList
     * @return
     */
//    private Object sxpClazzResultInfo(List<Classify> classifyList) {
//        List<String> clazzIDs = new ArrayList<String>();
//        for (Classify classify : classifyList) {
//            clazzIDs.add(classify.getClazzid());
//        }
//        DataResult result = restTemplate.postForObject(cfg.getSxpGoodsUrl() + "/goods/rateList", clazzIDs, DataResult.class);
//        if (result.getIsSuccess() == 0) {
//            throw new ServiceException("查询扣点值失败");
//        }
//        Map<String, Object> valList = (Map<String, Object>) result.getData();
//        List<ClassifyWithValVo> cwvvs = new ArrayList<ClassifyWithValVo>();
//        for (Classify classify : classifyList) {
//            ClassifyWithValVo cwvv = new ClassifyWithValVo();
//            BeanUtils.copyProperties(classify, cwvv);
//            if (valList.containsKey(classify.getClazzid())) {
//                cwvv.setClazzVal(valList.get(classify.getClazzid()));
//            }
//            cwvvs.add(cwvv);
//        }
//        return cwvvs;
//    }


    /***************************************/

    public int deleteByPrimaryKey(Classify record) {
        record.setIsstop(1);
        return classifyMapper.updateByPrimaryKeySelective(record);
    }

    public int insertSelective(Classify record) {
        if (record.getClazzparentid() == null || record.getClazzparentid().equals("")) {
            record.setLevel(1);
        } else {
            Classify temp = new Classify();
            temp = classifyMapper.selectByPrimaryKey(record.getClazzparentid());
            if (temp == null) {
                throw CommonTools.createException(ErrorCodeEnum.handleClassifyFailure);
            } else {
                record.setLevel(temp.getLevel() + 1);
            }
        }
        return classifyMapper.insertSelective(record);
    }

    public Classify selectByPrimaryKey(String clazzid) {
        classify = new Classify();
        classify = classifyMapper.selectByPrimaryKey(clazzid);
        if (classify == null) {
            throw new ServiceException("类别id不存在", RestConst.ErrorCode.DATABASE_ERROR);
        }
        return classify;
    }

    public List<Map<String, Object>> selectByIDs(List<String> ids) {
        return classifyMapper.selecteByIDs(ids);
    }

    public Object selectByclazzparentid(String clazzparentid) {
        List<Classify> classifyList = classifyMapper.selectByclazzparentid(clazzparentid);
        if (classifyList.size() > 0 && classifyList.get(0).getClazztype() == 6) {
           // return this.sxpClazzResultInfo(classifyList);
            return classifyList;
        } else {
            return classifyList;
        }
    }

    public int updateByPrimaryKeySelective(Classify record) {
        if (record.getClazzparentid() == null || record.getClazzparentid().equals("")) {
            record.setLevel(1);
        } else {
            Classify temp = new Classify();
            temp = classifyMapper.selectByPrimaryKey(record.getClazzparentid());
            if (temp == null) {
                throw CommonTools.createException(ErrorCodeEnum.parmIsNull);
            } else {
                record.setLevel(temp.getLevel() + 1);
            }
        }

        return classifyMapper.updateByPrimaryKeySelective(record);
    }


    public Object selectAllPlatform() {
        return classifyMapper.selectAllPlatform();
    }


}
